package com.easipass.exangeservice.monitor;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.easipass.exangeservice.MsgListener;
import com.easipass.exangeservice.MsgMonitor;
import com.easipass.exangeservice.msg.FileMsg;
import com.easipass.exangeservice.msg.Msg;
import com.easipass.unifiedconfig.ConfigManager;
import com.easipass.unifiedconfig.InsufficientPrivillageException;
import com.easipass.unifiedconfig.NotFoundException;
import com.easipass.unifiedconfig.Parameter;
import com.easipass.unifiedconfig.UCI;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2010-2-4
 */
public class UnicFileMsgMonitor implements MsgMonitor {
	protected final Log log = LogFactory.getLog(this.getClass());
	
	public static final String PARA_MONITOR_PATH = "monitor_path";
	
	private UCI paramodule;
	
	private MsgListener listener;
	
	private ConfigManager configManager;
	
	private Timer timer;
	
	private long period = -1;
	
	private TimerTask t = new TimerTask() {
		
		@Override
		public void run() {
			scan();
		}

	};
	
	public UnicFileMsgMonitor(UCI paramodule) {
		this.paramodule = paramodule;
	}
	
	public MsgListener getMsgListener() {
		return listener;
	}

	public void setMsgListener(MsgListener listener) {
		this.listener = listener;
	}
	public synchronized void start() {
		if(timer != null)
			timer.cancel();
		timer = new Timer();
		timer.scheduleAtFixedRate(t, 1000, period);
	}

	public synchronized void stop() {
		if(timer != null)
			timer.cancel();
		timer = null;
	}

	protected String[] getMonitorPathes(UCI u) {
		Parameter p = null;
		try {
			p = configManager.getParameter(u);
			return p.getValues();
		} catch (NotFoundException e1) {
			log.warn(e1);
		} catch (InsufficientPrivillageException e1) {
			log.warn(e1);
		}
		return new String[0];
	}
	
	protected void scan() {
		
		
		for(String monitorPath : getMonitorPathes(new UCI(paramodule, PARA_MONITOR_PATH))) {
			File mp = new File(monitorPath);
			if(!mp.exists()) continue;
			
			for(File f : mp.listFiles()) {
				if(!f.isFile()) continue;
				try {
					FileMsg msg = new FileMsg(f);
					msg.setAttribute(Msg.ATTR_SENDER, paramodule.getAccount());
					if(listener != null)
						listener.onMsg(msg);
				} catch (IOException e) {
					log.error(e, e);
				}
			}
		}
	}

	@Override
	protected void finalize() throws Throwable {
		stop();
	}

	public ConfigManager getConfigManager() {
		return configManager;
	}

	public void setConfigManager(ConfigManager configManager) {
		this.configManager = configManager;
	}
	public long getPeriod() {
		return period;
	}
	public void setPeriod(long period) {
		this.period = period;
	}

}
